package me.zk.practice1.s;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author zhangkai
 * @date 2023/7/7 16:18
 */
public class LS142 {
    public ListNode detectCycle(ListNode head) {

        Set<ListNode> set = new HashSet<>();
        ListNode pre = head;
        while (pre != null) {
            if (!set.contains(pre)) {
                set.add(pre);
                pre = pre.next;
            } else {
                return pre;
            }

        }
        return null;
    }

    public ListNode detectCycle2(ListNode head) {

        ListNode fast = head, slow = head;
        while (true) {
            if (fast == null || fast.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) break;
        }
        fast = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;


    }
}
